﻿using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebPartPages;
using System.IO;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.Serialization;
using System.Web.UI.HtmlControls;
using System.Reflection;

namespace Webcoda.SP.WP.Toolparts {

    public class PickerToolPart : ToolPart, INamingContainer {
        public List<PickerItem> Items { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="PickerToolPart"/> class.
        /// </summary>
        public PickerToolPart()
            : base() {
            Items = new List<PickerItem>();
        }

        /// <summary>
        /// Registers the script to load the web selector.
        /// </summary>
        void RegisterPopupScript() {
            StringBuilder sb = new StringBuilder();
            sb.Append("function cust_launchPickerSite(inputID)\r\n {\r\n  if (!document.getElementById) return;");
            sb.Append("var targetTextBox = document.getElementById(");
            sb.Append("inputID");
            sb.Append(");");
            sb.Append("if (targetTextBox == null) return;");
            sb.Append("var serverUrl = '");
            sb.Append(SPContext.Current.Web.ServerRelativeUrl);
            sb.Append("';var callbackSite = function(results){if (results == null || results[1] == null) return;targetTextBox.value = results[1];};\r\n");
            sb.Append("LaunchPickerTreeDialog('CbqPickerSelectSiteTitle','CbqPickerSelectSiteText','websOnly','',serverUrl, '','','','/_layouts/images/smt_icon.gif','', callbackSite);}");
            this.Page.ClientScript.RegisterClientScriptBlock(typeof(PickerToolPart), "PickerSite", sb.ToString(), true);

            sb = new StringBuilder();
            sb.Append("function cust_launchPickerList(inputID) {\r\n");
            sb.Append("    if (!document.getElementById) return;");
            sb.Append("    var targetTextBox = document.getElementById(");sb.Append("inputID");sb.Append(");");
            sb.Append("    if (targetTextBox == null) return;");
            sb.Append("    var serverUrl = '");sb.Append(SPContext.Current.Web.ServerRelativeUrl);sb.Append("';");
            sb.Append("    var callbackList = function(results){");
            sb.Append("        if (results == null || results[1] == null || results[2] == null)");
            sb.Append("            return;");
            sb.Append("        targetTextBox.value = '/_layouts/listfeed.aspx?List=' + ");
            sb.Append("        results[0].split('?')[0].split('SPList:')[1]");
            sb.Append("    };\r\n");
            sb.Append("    LaunchPickerTreeDialog('CbqPickerSelectListTitle','CbqPickerSelectListText','listsOnly','',serverUrl, '','','','/_layouts/images/smt_icon.gif','', callbackList);");
            sb.Append("}");
            this.Page.ClientScript.RegisterClientScriptBlock(typeof(PickerToolPart), "PickerList", sb.ToString(), true);

            this.Page.ClientScript.RegisterClientScriptInclude("PickerTreeDialog", "/_layouts/1033/PickerTreeDialog.js");
        }

        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load"/> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs"/> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e) {
            base.OnLoad(e);
            RegisterPopupScript();
        }

        /// <summary>
        /// Gets a property value of an object by reflection.
        /// </summary>
        /// <param name="target">Target object.</param>
        /// <param name="name">Name of the property.</param>
        /// <returns>The property value.</returns>
        object GetPropertyValue(object target, string name) {
            try {
                PropertyInfo pi = target.GetType().GetProperty(name);
                return pi.GetValue(target, null);
            } catch {
                return "##error##";
            }
        }

        /// <summary>
        /// Sets a property value of an object by reflection.
        /// </summary>
        /// <param name="target">Target object.</param>
        /// <param name="name">Name of the property.</param>
        /// <param name="value">The value to set.</param>
        /// <returns>The property value.</returns>
        void SetPropertyValue(object target, string name, object value) {
            PropertyInfo pi = target.GetType().GetProperty(name);
            pi.SetValue(target, value, null);
        }

        private Label uiLblExtSource;
        private Label uiLblIntSource;
        private RadioButton uiRbRssInternal;
        private RadioButton uiRbRssExternal;
        private TextBox uiTxtRssInternal;
        private TextBox uiTxtRssExternal;

        protected override void CreateChildControls() {
            WebPart parent = this.ParentToolPane.SelectedWebPart;

            //External Label
            uiLblExtSource = new Label();
            uiLblExtSource.Text = "External RSS Source:";
            uiLblExtSource.Attributes.Add("style", "margin-left:10px;");
            this.Controls.Add(uiLblExtSource);

            uiTxtRssInternal = new TextBox();
            uiTxtRssExternal = new TextBox();

            //create External Radio Button
            uiRbRssExternal = new RadioButton();
            uiRbRssExternal.ID = "uiRbRssExternal";
            //uiRbRssExternal.GroupName = "RSS";
            uiRbRssExternal.Attributes.Add("name", "uiRbRssExternal");
            uiRbRssExternal.Attributes.Add("onclick", "SetDisabled('uiRbRssInternal', 'uiTxtRssInternal');SetEnabled('uiRbRssExternal', 'uiTxtRssExternal');");
            if (!(bool)GetPropertyValue(parent, "PEE_LinkRelativeURL")) {
                uiRbRssExternal.Checked = true;
                uiTxtRssInternal.Attributes["disabled"] = "true";
            }
            
            //create External TextBox
            if (!(bool)GetPropertyValue(parent, "PEE_LinkRelativeURL")) {
                uiTxtRssExternal.Text = (string)GetPropertyValue(parent, "PA_RssFeedUrl");
            }
            uiTxtRssExternal.Attributes.Add("ms-tlpnwiden", "true");
            uiTxtRssExternal.Attributes.Add("onclick", "SetDisabled('uiRbRssInternal', 'uiTxtRssInternal');SetEnabled('uiRbRssExternal', 'uiTxtRssExternal');");
            uiTxtRssExternal.Style.Add(HtmlTextWriterStyle.Width, "176px");
            uiTxtRssExternal.ID = "uiTxtRssExternal";

            //Internal Label
            uiLblIntSource = new Label();
            uiLblIntSource.Text = "Internal RSS Source:";
            uiLblIntSource.Attributes.Add("style", "margin-left:10px;");
            this.Controls.Add(uiLblIntSource);

            //create Internal Radio Button
            uiRbRssInternal = new RadioButton();
            uiRbRssInternal.ID = "uiRbRssInternal";
            //uiRbRssInternal.GroupName = "RSS";
            uiRbRssInternal.Attributes.Add("name", "uiRbRssInternal");
            uiRbRssInternal.Attributes.Add("onclick", "SetEnabled('uiRbRssInternal', 'uiTxtRssInternal');SetDisabled('uiRbRssExternal', 'uiTxtRssExternal');");
            if ((bool)GetPropertyValue(parent, "PEE_LinkRelativeURL")) {
                uiRbRssInternal.Checked = true;
                uiTxtRssExternal.Attributes["disabled"] = "true";
            }

            //create Internal TextBox
            if ((bool)GetPropertyValue(parent, "PEE_LinkRelativeURL")) {
                uiTxtRssInternal.Text = (string)GetPropertyValue(parent, "PA_RssFeedUrl");
            }
            uiTxtRssInternal.Attributes.Add("ms-tlpnwiden", "true");
            uiTxtRssInternal.Attributes.Add("onclick", "SetEnabled('uiRbRssInternal', 'uiTxtRssInternal');SetDisabled('uiRbRssExternal', 'uiTxtRssExternal');");
            uiTxtRssInternal.Style.Add(HtmlTextWriterStyle.Width, "176px");
            uiTxtRssInternal.ID = "uiTxtRssInternal";


            base.CreateChildControls();
        }

        /// <summary>
        /// Sends the tool part content to the specified HtmlTextWriter object, which writes the content to be rendered on the client.
        /// </summary>
        /// <param name="output">The HtmlTextWriter object that receives the tool part content.</param>
        protected override void RenderToolPart(HtmlTextWriter output) {
            WebPart parent;
            int i = 0;

            parent = this.ParentToolPane.SelectedWebPart;

            if (Items.Count > 0) {

                output.Write("<script type='text/javascript'>");
                output.Write(@"function SetEnabled(rbID, txtBoxID){
                                   $('#' + txtBoxID + '').attr('disabled', false);
                                   $('#' + rbID + '').attr('checked', true);
                                }");
                output.Write(@"function SetDisabled(rbID, txtBoxID){
                                   $('#' + txtBoxID + '').attr('disabled', true);
                                   $('#' + rbID + '').attr('checked', false);
                                }");
                output.Write("</script>");

                //uiLblExtSource.RenderControl(output);
                //output.Write("<br/>");
                //uiRbRssExternal.RenderControl(output);
                //uiTxtRssExternal.RenderControl(output);

                //output.Write("<br/>");
                //output.Write("<br/>");

                //uiLblIntSource.RenderControl(output);
                //output.Write("<br/>");
                //uiRbRssInternal.RenderControl(output);
                //uiTxtRssInternal.RenderControl(output);

                output.Write("<table cellspacing=\"0\" border=\"0\" style=\"border-width:0px;width:100%;border-collapse:collapse;\">");

                foreach (PickerItem pi in Items) {
                    output.Write("<tr><td>");
                    output.Write("<div class=\"UserSectionHead\">");
                    output.Write("External RSS Source");
                    output.Write("</div>");
                    output.Write("<div class=\"UserControlGroup\"><nobr>");
                    uiRbRssExternal.RenderControl(output);
                    uiTxtRssExternal.RenderControl(output);
                    output.Write("</nobr></div>");
                    output.Write("</td></tr>");
                    output.Write("<tr><td>");
                    output.Write("<div class=\"UserSectionHead\">");
                    output.Write(pi.Title);
                    output.Write("</div>");
                    output.Write("<div class=\"UserControlGroup\"><nobr>");
                    uiRbRssInternal.RenderControl(output);
                    uiTxtRssInternal.RenderControl(output);
                    //output.Write("<input type=\"text\" ms-tlpnwiden='true' style='width:156px;' ");
                    //output.Write("value=\"" + GetPropertyValue(parent, pi.PropertyName) + "\"");
                    //output.Write(" name=\"picker_" + i.ToString() + "\" id=\"picker_" + i.ToString() + "\"/>");
                    output.Write("<input type=\"button\" onclick=\"SetEnabled('uiRbRssInternal', 'uiTxtRssInternal');SetDisabled('uiRbRssExternal', 'uiTxtRssExternal');" + (pi.PickerType == PickerType.Site ? "cust_launchPickerSite" : "cust_launchPickerList"));
                    output.Write("('uiTxtRssInternal'); return false;\" value=\"...\"/>");

                    output.Write("</nobr></div>");
                    output.Write("</td></tr>");
                    i++;
                }

                output.Write("</table>");
            }
        }

        /// <summary>
        /// Called when the user clicks the OK or the Apply button in the tool pane.
        /// </summary>
        public override void ApplyChanges() {
            WebPart parent;
            int i = 0;

            parent = ParentToolPane.SelectedWebPart;

            if (Items.Count > 0) {
                foreach (PickerItem pi in Items) {
                    if (!string.IsNullOrEmpty(Page.Request.Form["uiRbRssInternal"])) {
                        SetPropertyValue(parent, pi.PropertyName, Page.Request.Form["uiTxtRssInternal"]);
                        SetPropertyValue(parent, "PEE_LinkRelativeURL", true);
                    } else {
                        SetPropertyValue(parent, pi.PropertyName, Page.Request.Form["uiTxtRssExternal"]);
                        SetPropertyValue(parent, "PEE_LinkRelativeURL", false);
                    }
                    i++;
                }
            }
        }


        public enum PickerType {
            Site,
            List
        }

        public class PickerItem {
            public string Title { private set; get; }
            public string PropertyName { private set; get; }
            public PickerType PickerType { private set; get; }

            public PickerItem(string title, string propertyName, PickerType pickerType) {
                Title = title;
                PropertyName = propertyName;
                PickerType = pickerType;
            }
        }
    }

    public partial class x : System.Web.UI.Page, IPostBackEventHandler {
        public void RaisePostBackEvent(string eventArgument) {
            string[] events = eventArgument.Split(',');
            switch (events[0].Trim()) {

                case "PICKER":
                    PickerParameterParser(events[1]);
                    break;
            }
        }
        private void PickerParameterParser(string pickerParams) {
            string[] param = pickerParams.Split(new char[] { '§' }, StringSplitOptions.RemoveEmptyEntries);
        }
    }

    
}